import cv2
#https://www.bilibili.com/video/BV1w3411N76g

def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
#缩小图像
# def smallByN(img, n):
#     x, y = img.shape[0:2]
#     return cv2.resize(img,(int(y/n),int(x/n)))

# 读取拼接图片
img1 = cv2.imread("D:\\data\\real\\BW\\0.JPG",0)
img2 = cv2.imread("D:\\data\\real\\BW\\1.JPG",0)

sift = cv2.SIFT_create()

(kp1, des1) = sift.detectAndCompute(img1, None)
(kp2, des2) = sift.detectAndCompute(img2, None)
#缩小图像，否则后面会报错：trainDescCollection[iIdx].rows < IMGIDX_ONE
#2^18=262144
if(len(des1)>=262144 or len(des2) >= 262144):
    # img1 = smallByN(img1,3)
    # img2 = smallByN(img2,3)
    sift = cv2.SIFT_create(nfeatures=5000,edgeThreshold=200)
    (kp1, des1) = sift.detectAndCompute(img1, None)
    (kp2, des2) = sift.detectAndCompute(img2, None)
# 1:1匹配
bf = cv2.BFMatcher(crossCheck=True)#蛮力匹配互相检测匹配
matches = bf.match(des1,des2)
matches = sorted(matches,key=lambda x: x.distance)
print("len(matches):"+str(len(matches)))

# k对最佳匹配
# bf = cv2.BFMatcher() #cv2.FlannBasedMatcher:快速完成操作
# matches = bf.knnMatch(des1,des2,k=2)
# good = []
# for m,n in matches:
#     if m.distance < 0.75 * n.distance:
#         good.append([m])
# print("len(good):"+str(len(good)))
#灰度转彩色，以便于画图
img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2RGB)
img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2RGB)
imgShow = cv2.drawMatches(img1,kp1,img2,kp2,matches[:100],None,flags=2)
#imgShow = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good[:100],None,flags=2)
cv2.imwrite("matches-sift-knn.jpg", imgShow)

